package android.medicalcloud.com.yiapp.yilian.ui.view;

import android.content.Context;
import android.medicalcloud.com.yiapp.R;
import android.medicalcloud.com.yiapp.base.utils.Logger;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;


/**
 * Created by yinshilin on 16-10-18.
 */
public class MainPageIndicator extends LinearLayout {
    ViewPager mViewPager;
    Context context;
    int size;
    int currentPage;
    public MainPageIndicator(Context context) {
        this(context, null);
    }

    public MainPageIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        setOrientation(HORIZONTAL);
    }

    public void setViewPager(ViewPager view) {
        if (mViewPager == view) {
            return;
        }
        if (mViewPager != null) {
            mViewPager.setOnPageChangeListener(null);
        }
        if (view.getAdapter() == null) {
            throw new IllegalStateException("ViewPager does not have adapter instance.");
        }

        mViewPager = view;
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                try {
                    currentPage = position%size;
                    for (int i = 0; i < getChildCount(); i++) {
                        getChildAt(i).findViewById(R.id.image).setEnabled(true);
                    }
                    getChildAt(position % size).findViewById(R.id.image).setEnabled(false);
                }catch (Exception E){

                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void setSize(int size) {
        this.size = size;
        init();
    }

    private void init() {
        removeAllViews();
        for (int i = 0; i < size; i++) {
            View view = LayoutInflater.from(context).inflate(R.layout.view_indicator, null);
            addView(view);
        }
        getChildAt(currentPage).findViewById(R.id.image).setEnabled(false);
    }
}
